<template>
  <div class="staffTrack-container">
    <div class="head">
      <!-- <div class="time">日期: {{ moment().format("YYYY-MM-DD") }}</div> -->
      <el-date-picker v-if="showDetail" v-model="datetimeValue" type="datetimerange" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" style="margin-left: 15px;">
      </el-date-picker>
      <el-button v-if="showDetail" slot="append" icon="el-icon-search" @click="showMove()">查看轨迹</el-button>
      <div class="tip">{{ title }}</div>
      <el-switch v-show="!showDetail" v-model="switchvalue" active-text="卫星图" inactive-text="简易图" class="switch"
        @change="changeSwitch"></el-switch>
    </div>
    <div class="head-box">
      <div v-if="showDetail" class="head-checkbox"><el-checkbox v-model="checked"
          @change="changeRange">作业区域</el-checkbox></div>
      <el-button v-if="showDetail" type="primary" icon="el-icon-refresh-right" circle @click="back"></el-button>
    </div>
    <div class="trajectory">
      <div id="map" style="height: 85vh;" ref="map"></div>
      <div class="info-box">
        <el-input placeholder="姓名" v-model="searchQuery">
          <el-button slot="append" icon="el-icon-search" @click="searchName()">搜索</el-button>
        </el-input>
        <div class="form-box">
          <ul v-infinite-scroll="load" style="overflow:auto;height:78vh;padding:0 10px" v-loading="loading">
            <div v-for="(item, index) in personData" :key="index">
              <div @click="showTrajectory(item)">
                <div class="info-icon"><i class="el-icon-location-outline"
                    style="color:#2677e0;margin-right: 10px;"></i>{{ item.name }}
                </div>
                <div class="box-title">状态：<span class="box-status">{{ item.online == 0 ? '作业中' : '不在线' }}</span></div>
                <div class="box-title">告警信息：<span class="box-tip">--</span></div>
                <div class="box-title">手机号：{{ item.phone }}</div>
                <div class="box-title">定位位置：{{ item.trajectory ? [parseFloat(item.trajectory.areaLocation.longitude),
                parseFloat(item.trajectory.areaLocation.latitude)] : '' }}</div>
                <div class="box-title">更新时间：{{ item.trajectory ? item.trajectory.createTime : '--' }}</div>
              </div>
              <div class="box-divider" />
            </div>
            <el-divider>没有更多了</el-divider>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { trajectoryList, trajectoryDetail } from "@/api/system/trajectory";
import moment from "moment";
import { getArea } from "@/api/system/area";
import { createMap, defaultMapOptions, getLocationName } from '@/utils/map.js';
import employeesIcon from '@/assets/images/bigScreen/worker.png';
export default {
  data() {
    return {
      cdn: process.env.VUE_APP_CDN_HOST,
      searchQuery: '',
      center: [116.122046, 24.288832], //梅州市
      map: null,
      personData: [], // 存储人员数据
      markers: [], // 存储地图标记
      zoom: 12, //地图缩放级别
      walking: null, //地图驾驶信息
      checked: false,
      showcheck: true,
      person: {}, // 用于存储当前选中人员信息
      path: [], //员工工作区域
      loading: true,
      title: '人员轨迹列表',
      datetimeValue: this.getDefaultDateRange(),
      showDetail: false,
      layers: [],
      switchvalue: false,
      tileLayer: null, //卫星图层
      polygon: null,
      layer: null,
    };
  },
  computed: {
    filteredPersonData() {
      // 根据搜索查询过滤人员数据
      if (!this.searchQuery) {
        return this.personData;
      }
      return this.personData.filter(person =>
        person.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      );
    },
  },
  async mounted() {
    await this.initMap();
    await this.fetchPersonData();
  },
  methods: {
    getDefaultDateRange() {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const endDate = new Date(today);
      endDate.setHours(23, 59, 59, 999);
      return [today, endDate];
    },
    async back() {
      this.title = '人员轨迹列表'
      this.showcheck = true
      this.checked = false;
      if (this.walking != null) {
        this.walking.clear()
      }
      await this.initMap();
      this.updateMarkers();
      this.datetimeValue = this.getDefaultDateRange(),
      this.showDetail = false,
      this.switchvalue = false,
      this.tileLayer = null;
    },
    async load() { },
    async changeSwitch() {
      if (this.map) {
        if (this.switchvalue) {
          // 切换到卫星图
          this.map.setMapType('satellite');
        } else {
          // 切换回标准地图
          this.map.setMapType('normal');
        }
      } else {
        console.error('Map is not initialized');
      }
    },
    async changeRange() {
      if (this.walking != null) {
        this.walking.clear()
      }
      if (this.checked) {
        const response = await getArea(this.person.areaId);
        const coordinates = response.data.areaLocations.map(location => [
          parseFloat(location.longitude),
          parseFloat(location.latitude)
        ]);
        this.path = coordinates;
        this.showTrajectoryRange()
      } else {
        if (this.polygon) {
          this.map.remove(this.polygon);
          this.polygon = null;
        }
        return
      }
    },
    async showMove() {
      if (this.datetimeValue && this.datetimeValue.length === 2) {
        const params = {
          id: this.person.id,
          startTime: moment(this.datetimeValue[0]).format('YYYY-MM-DD HH:mm:ss'),
          endTime: moment(this.datetimeValue[1]).format('YYYY-MM-DD HH:mm:ss'),
        }
        const res = await trajectoryList(params)
        this.person = res.data[0];
        this.addTrackLayer(this.person.name, this.person.employeeTrajectories)
        this.checked = false
      }
    },
    async initMap() {
      try {
        this.map = await createMap(this.$refs.map, {
          ...defaultMapOptions,
          zoom: 11,
          minZoom: 3,
          maxZoom: 20
        }, ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType']);

        // 添加地图控件
        this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.Scale());
      } catch (error) {
        console.error('地图初始化失败:', error);
      }
    },
    async fetchPersonData() {
      this.loading = true
      const res = await trajectoryList()
      if (res.code == 200) {
        this.personData = res.data;
        this.updateMarkers();
      }
      this.loading = false
    },
    //人员分布点
    updateMarkers() {
      // 清除旧标记
      this.markers.forEach(marker => this.map.remove(marker));
      this.markers = []; // 重置标记数组

      // 点击标记时显示信息窗口
      this.filteredPersonData.forEach(async (person, index) => {
        if (person.trajectory) {
          const location = [parseFloat(person.trajectory.areaLocation.longitude), parseFloat(person.trajectory.areaLocation.latitude)];

          // 创建信息窗体内容
          const infoWindowContent = `
            <div style="background-color: #fff;font-size: 14px;width: 350px;background-size: cover;">
              <div style="width: 100%;padding: 5px 10px;background: #ccced1;">${person.name}</div>
              <div style="display: flex;margin: 0 10px;">
                <img src="${this.cdn + person.photo}" style="width: 80px;height: 100px;margin-top: 5px;" />
                <div style="color: #2677e0;margin-left: 8px;">
                  <div>状态：<span style="color: bisque;">作业中</span></div>
                  <div>告警信息：<span style="color: black;">--</span></div>
                  <div>手机号：${person.phone}</div>
                  <div>定位位置：${location}</div>
                  <div>更新时间：${person.trajectory.createTime}</div>
                  <div style="color:#e90fcc;margin-top:5px;text-decoration: underline;cursor: pointer;" onclick="viewTrajectory('${person.id}')">查看作业轨迹</div>
                </div>
              </div>
            </div>`;

          // 根据 index 计算随机偏移量（0-10）
          const randomOffsetX = Math.floor(Math.random() * 11) - 10;

          // 创建标记点
          const marker = new AMap.Marker({
            position: location,
            icon: new AMap.Icon({
              imageSize: new AMap.Size(30, 30),
              offset: new AMap.Pixel(randomOffsetX, 0),
              image: employeesIcon
            }),
            title: person.name
          });

          // 创建信息窗体
          const infoWindow = new AMap.InfoWindow({
            content: infoWindowContent,
            closeOnClick: false
          });

          // 添加点击事件
          marker.on('click', () => {
            infoWindow.open(this.map, location);
          });

          // 添加到地图
          this.map.add(marker);
          this.markers.push(marker);

          // 添加全局函数供信息窗体调用
          window.viewTrajectory = (id) => {
            this.person = person;
            this.addTrackLayer(person.name, person.employeeTrajectories);
          };
        }
      });
    },
    //轨迹图
    addTrackLayer(name, coordinates) {
      this.title = name + '轨迹图'
      this.showDetail = true;

      // 清除现有标记和轨迹
      this.markers.forEach(marker => this.map.remove(marker));
      this.markers = [];

      if (this.layer) {
        this.map.remove(this.layer);
        this.layer = null;
      }

      const uniqueCoordinates = Array.from(new Set(coordinates.map(item => `${item.areaLocation.longitude},${item.areaLocation.latitude}`)));
      if (uniqueCoordinates.length < 2) {
        this.$message({
          message: '该时间段没有轨迹数据',
          type: 'error'
        });
        return;
      }

      const trackPoints = coordinates.map(item => [
        parseFloat(item.areaLocation.longitude),
        parseFloat(item.areaLocation.latitude)
      ]);

      // 创建轨迹线
      this.layer = new AMap.Polyline({
        path: trackPoints,
        strokeColor: "#ff0000",
        strokeWeight: 3,
        strokeOpacity: 0.8,
        showDir: true
      });

      this.map.add(this.layer);

      // 添加起点标记
      const startMarker = new AMap.Marker({
        position: trackPoints[0],
        icon: new AMap.Icon({
          size: new AMap.Size(25, 25),
          image: 'data:image/svg+xml;base64,' + btoa(`
            <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25">
              <circle cx="12" cy="12" r="10" fill="#ffff00" stroke="#ff0000" stroke-width="2"/>
              <text x="12" y="16" text-anchor="middle" font-size="12" fill="#ff0000">S</text>
            </svg>
          `)
        }),
        title: '起点'
      });
      this.map.add(startMarker);
      this.markers.push(startMarker);

      // 添加终点标记
      const endMarker = new AMap.Marker({
        position: trackPoints[trackPoints.length - 1],
        icon: new AMap.Icon({
          size: new AMap.Size(25, 25),
          image: 'data:image/svg+xml;base64,' + btoa(`
            <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25">
              <circle cx="12" cy="12" r="10" fill="#00ff00" stroke="#ff00ff" stroke-width="2"/>
              <text x="12" y="16" text-anchor="middle" font-size="12" fill="#ff00ff">E</text>
            </svg>
          `)
        }),
        title: '终点'
      });
      this.map.add(endMarker);
      this.markers.push(endMarker);

      // 设置地图中心和缩放级别
      const center = trackPoints[Math.floor(trackPoints.length / 2)];
      this.map.setCenter(center);
      this.map.setZoom(14);
    },
    createMarkerEl(title, id, type, data) {
      const that = this;
      const customData = JSON.stringify(data);
      const el = document.createElement('div');
      el.setAttribute('data-id', id);
      el.setAttribute('data-customData', customData);
      el.setAttribute('data-type', type);
      el.addEventListener('click', function (e) {
        const target = e.target;
        const dataset = target.dataset;
        const { customdata: newData = '', type = '' } = dataset;
        if (!type) return false;
        const res = JSON.parse(newData);
        that.currentAction = {
          type,
          data: res,
        };
      });
      el.innerHTML = `
      <div style="position: relative;width: max-content;cursor: pointer;display: flex;flex-direction: column;">
      <div data-customData=${customData} data-type="${type}" style="color: #fff;font-size: 14px;border: 1px solid #00e676;margin-bottom: 5px">${title}</div>
      <img data-customData=${customData} data-type="${type}" src=${employeesIcon} style="height: 25px;width: 30px;">
</div>
      `
      return el;
    },
    //员工轨迹范围
    showTrajectoryRange() {
      this.polygon = new AMap.Polygon({
        path: this.path,
        strokeColor: '#ffffff',
        strokeWeight: 2,
        strokeOpacity: 0.8,
        fillColor: '#1791fc',
        fillOpacity: 0.3
      });
      this.map.add(this.polygon);

      const [longitude, latitude] = this.getPolygonCenter(this.path);
      this.map.setCenter([longitude, latitude]);
      this.map.setZoom(13);
    },
    //取消范围
    removeTrajectoryRange() {
      return new Promise((resolve, reject) => {
        try {
          if (this.polygon) {
            this.map.remove(this.polygon);
            this.polygon = null;
          }
          resolve();
        } catch (error) {
          reject(error);
        }
      });
    },
    async showTrajectory(person) {
      if (this.polygon) {
         this.map.remove(this.polygon);
         this.polygon = null;
      }
      this.checked = false;
      const params = {
        id: person.id,
        startTime: moment(this.datetimeValue[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(this.datetimeValue[1]).format('YYYY-MM-DD HH:mm:ss'),
      }
      const res = await trajectoryList(params)
      this.person = res.data[0];
      // 转换为所需格式
      this.addTrackLayer(this.person.name, this.person.employeeTrajectories);
      this.showDetail = true;
    },
    //根据name搜索人员
    async searchName() {
      if (this.searchQuery) {
        const res = await trajectoryDetail({
          content: this.searchQuery
        })
        if (res.code === 200) {
          this.personData = res.data.records
        }
        else {
          this.$modal.msgError(res.msg)
        }
      }
    },
    getPolygonCenter(paths) {
      let total = paths.length;
      let X = 0;
      let Y = 0;
      let Z = 0;
      paths.forEach((lnglat) => {
        let lng = lnglat[0] * Math.PI / 180;
        let lat = lnglat[1] * Math.PI / 180;
        let x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;

      let Lng = Math.atan2(Y, X);
      let Hyp = Math.sqrt(X * X + Y * Y);
      let Lat = Math.atan2(Z, Hyp);
      return [Lng * 180 / Math.PI, Lat * 180 / Math.PI];
    },
    //时间格式
    async formatDateString(dateString) {
      // 提取月、日和时间
      const [datePart, timePart] = dateString.split(' ');
      const [year, month, day] = datePart.split('-');
      // 返回格式化的字符串
      return `${month}-${day} ${timePart}`;
    },
  },
};
</script>

<style lang="scss">
/* 自定义样式 */
#map {
  width: 100%;
  height: 400px;
}

.staffTrack-container {
  height: 0vh;
  padding: 10px 0;

  .switch {
    margin-right: 20px;
  }

  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .time {
    text-align: left;
  }

  .tip {
    text-align: center;
    flex-grow: 1;
  }

  .head-box {
    position: absolute;
    top: 8%;
    left: 10px;
    z-index: 999;
    display: flex;
    align-items: center;

    .head-checkbox {
      padding: 7px 12px;
      background-color: #ffffff;
      margin: 0 10px;
    }
  }

  .trajectory {
    margin-top: 10px;
    display: flex;

    .info-box {
      width: 20%;
      background: #ffffff;

      .form-box {

        .box-title {
          color: rgb(118, 235, 196);
          margin: 10px 0;
        }

        .box-tip {
          color: rgb(22, 22, 22);
        }

        .box-status {
          color: rgb(201, 149, 80);
        }

        .box-divider {
          width: 98%;
          height: 1px;
          background: #b9b8b8;
          margin: 20px auto;
        }
      }
    }
  }

  #panel {
    position: fixed;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 95px;
    right: 17.1%;
    width: 300px;
  }

  #panel .amap-call {
    background-color: #009cf9;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }

  #panel .amap-lib-driving {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow: hidden;
  }

  .aimap-popup-content {
    background: center;
  }

}
</style>
